<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { RoomApi } from '#/api/spa/room';

import RoomEnvironmentForm from './room-environment-form.vue';
import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { ref, computed, nextTick, watch } from 'vue';
import { $t } from '#/locales';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';

import {
  deleteRoomEnvironment,
  getRoomEnvironmentPage,
} from '#/api/spa/room/environment';
import {
  useRoomEnvironmentGridFormSchema,
  useRoomEnvironmentGridColumns,
} from '../environment/data';
import { isEmpty } from '@vben/utils';

const props = defineProps<{
  roomId?: number; // 房间ID（主表的关联字段）
}>();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: RoomEnvironmentForm,
  destroyOnClose: true,
});

/** 创建SPA房间环境监控 */
function handleCreate() {
  if (!props.roomId) {
    message.warning('请先选择一个房间信息!');
    return;
  }
  formModalApi.setData({ roomId: props.roomId }).open();
}

/** 编辑SPA房间环境监控 */
function handleEdit(row: RoomApi.RoomEnvironment) {
  formModalApi.setData(row).open();
}

/** 删除SPA房间环境监控 */
async function handleDelete(row: RoomApi.RoomEnvironment) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    key: 'action_process_msg',
  });
  try {
    await deleteRoomEnvironment(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useRoomEnvironmentGridFormSchema(),
  },
  gridOptions: {
    columns: useRoomEnvironmentGridColumns(),
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          if (!props.roomId) {
            return [];
          }
          return await getRoomEnvironmentPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            roomId: props.roomId,
            ...formValues,
          });
        },
      },
    },
    pagerConfig: {
      enabled: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
    height: '600px',
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
  } as VxeTableGridOptions<RoomApi.RoomEnvironment>,
});

/** 刷新表格 */
async function onRefresh() {
  await gridApi.query();
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.roomId,
  async (val) => {
    if (!val) {
      return;
    }
    await nextTick();
    await onRefresh();
  },
  { immediate: true },
);
</script>

<template>
  <FormModal @success="onRefresh" />
  <Grid table-title="SPA房间环境监控列表">
    <template #toolbar-tools>
      <TableAction
        :actions="[
          {
            label: $t('ui.actionTitle.create', ['房间信息']),
            type: 'primary',
            icon: ACTION_ICON.ADD,
            auth: ['spa:room:create'],
            onClick: handleCreate,
          },
        ]"
      />
    </template>
    <template #actions="{ row }">
      <TableAction
        :actions="[
          {
            label: $t('common.edit'),
            type: 'link',
            icon: ACTION_ICON.EDIT,
            auth: ['spa:room:update'],
            onClick: handleEdit.bind(null, row),
          },
          {
            label: $t('common.delete'),
            type: 'link',
            danger: true,
            icon: ACTION_ICON.DELETE,
            auth: ['spa:room:delete'],
            popConfirm: {
              title: $t('ui.actionMessage.deleteConfirm', [row.id]),
              confirm: handleDelete.bind(null, row),
            },
          },
        ]"
      />
    </template>
  </Grid>
</template>
